<template>
   <div class="sdy-login">
      <SdyHeader title="啥都有 ~ 登录" back></SdyHeader>
      <van-form class="login-form" @submit="onSubmit">
         <van-cell-group inset>
            <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
               :rules="[{ required: true, message: '请填写用户名' }]" />

            <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
               :rules="[{ required: true, message: '请填写密码' }]" />
         </van-cell-group>
         <div class="register">
            还没有账号，<router-link to="/register">去注册</router-link>
         </div>
         <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
               登录
            </van-button>
         </div>
      </van-form>
   </div>
</template>
                          
  
<script setup lang="ts">
// 导入相关Api接口
import { loginApi } from "@/api/users"
import { ref } from 'vue'
import { Toast } from "vant";
import { useRouter, type Router } from "vue-router";
const username = ref<string>('')
const password = ref<string>('')

const $router: Router = useRouter()
const onSubmit = async () => {

   const res = await loginApi(username.value, password.value)
   // console.log(res);//code: '200', message: '登录成功', data: {…}}

   if (((res as unknown) as ({ code: string })).code === '200') {
      Toast({
         message: '登录成功',
         icon: 'phone-circle-o',
      });

      // 储存一下token 和 userid
      window.localStorage.setItem('userid',res.data.userid)
      window.localStorage.setItem('token',res.data.token)

      // 跳转到首页路由
      setTimeout(() => {
         $router.push('/home')
      }, 2000)

      return
   }

   Toast({
      message: '登录失败',
      icon: 'phone-circle-o',
   });

}
</script>
  
<style scoped lang="scss">
.sdy-login {
   height: 100%;
   display: flex;
   justify-content: center;
   align-items: center;

   >.login-form {
      border: 1px solid #333;
      border-radius: 10px;
      padding: 10px;

      >.register {
         font-size: 18px;
      }
   }

}
</style>